package yunquan.wang.base.web;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;

import yunquan.wang.base.dao.PropertyFilter;
import yunquan.wang.base.service.BaseService;
import yunquan.wang.base.utils.Reflections;

public abstract class BaseController<T> {
	public abstract BaseService<T> getService();
	protected  final Logger logger = LoggerFactory.getLogger(this.getClass());
	protected final String PAGE=WebConstants.ATTRIBUTE_PAGE;
	protected final String ENTITY=WebConstants.ATTRIBUTE_ENTITY;
	/**
	 * 基础查询类。
	 * @return
	 */
	protected ModelAndView baseList() {
		ModelAndView mv = new ModelAndView();
		List<PropertyFilter> filters = WebHelper.filterRequest(WebHelper.getRequest());
		Page<T> page = getService().findPage(WebHelper.getPage(), filters);
		mv.addObject(PAGE, page);
		return mv;
	}
	//Add  RedirectAttributes redirectAttributes
	//TODO
	protected ModelAndView baseSave(T entity,BindingResult bindingResult) {
		ModelAndView mv = new ModelAndView("redirect:list.do");
		getService().save(entity);
		return mv;
	}

	protected ModelAndView baseView() {
		String id = WebHelper.getRequestParam("id");
		ModelAndView mv = new ModelAndView();
		mv.addObject(ENTITY, getService().get(id));
		return mv;
	}
	protected ModelAndView baseInput() {
		String id = WebHelper.getRequestParam("id");
		ModelAndView mv = new ModelAndView();
		T entity = null;
		if (StringUtils.isNotBlank(id))
		{
			entity = getService().get(id);
		}
		else
		{
			entity=	(T) BeanUtils.instantiateClass(Reflections.getClassGenricType(getClass()));
		}
		mv.addObject(ENTITY, entity);
		return mv;
	}
	//Add  RedirectAttributes redirectAttributes
	//TODO
	protected ModelAndView baseDelete() {
		ModelAndView mv = new ModelAndView("redirect:list.do");
 
		String id = WebHelper.getRequestParam("id");
		getService().delete(id);
		return mv;
	}

}
